package com.lxt.ScreencastGallery;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.util.List;

/**
 * 缩略图列表适配器
 */
public class ThumbnailAdapter extends RecyclerView.Adapter<ThumbnailAdapter.ViewHolder> {
    private List<MediaItem2> mediaItems;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(MediaItem2 mediaItem);
    }

    public ThumbnailAdapter(List<MediaItem2> mediaItems) {
        this.mediaItems = mediaItems;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void updateData(List<MediaItem2> mediaItems) {
        this.mediaItems = mediaItems;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_thumbnail, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        MediaItem2 mediaItem = mediaItems.get(position);
        
        // 设置缩略图
        Glide.with(holder.itemView.getContext())
                .load(mediaItem.getFile())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(200, 200) // 限制缩略图大小
                .centerCrop()
                .into(holder.thumbnailImage);
        
        // 设置视频图标
        holder.videoPlayIcon.setVisibility(mediaItem.isVideo() ? View.VISIBLE : View.GONE);
        
        // 设置文件名（限制长度）
        String fileName = mediaItem.getName();
        if (fileName.length() > 15) {
            fileName = fileName.substring(0, 12) + "...";
        }
        holder.fileName.setText(fileName);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(mediaItem);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mediaItems != null ? mediaItems.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView thumbnailImage;
        ImageView videoPlayIcon;
        TextView fileName;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbnailImage = itemView.findViewById(R.id.thumbnail_image);
            videoPlayIcon = itemView.findViewById(R.id.video_play_icon);
            fileName = itemView.findViewById(R.id.file_name);
        }
    }
}
